package com.das.mechanic_alone.mvp.view.alone;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.das.mechanic_alone.R;
import com.das.mechanic_alone.R2;
import com.das.mechanic_alone.mvp.contract.alone.X3NewAloneServiceContract;
import com.das.mechanic_alone.mvp.presenter.alone.X3NewAloneServicePresenter;
import com.das.mechanic_base.adapter.alone.X3NewSearchServiceItemAdapter;
import com.das.mechanic_base.adapter.common.X3HomeSearchAdapter;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.bean.alone.AloneSearchBean;
import com.das.mechanic_base.bean.alone.NewServiceHeaderBean;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.greendao.AloneServiceListBean;
import com.das.mechanic_base.gen.DaoSessionUtils;
import com.das.mechanic_base.utils.X3AloneServiceSearchUtils;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.X3StatusBarUtil;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.widget.X3BottomAffirmMileDialog;
import com.das.mechanic_base.widget.X3NewBottomMileOrTimeDialog;
import com.das.mechanic_base.widget.X3PointDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static android.view.View.VISIBLE;

public class X3NewAloneSearchActivity extends X3BaseActivity<X3NewAloneServicePresenter> implements TextWatcher, X3HomeSearchAdapter.IOnSaveClick, X3NewAloneServiceContract.View, X3NewSearchServiceItemAdapter.IOnClickService, TextView.OnEditorActionListener, X3NewBottomMileOrTimeDialog.IOnAffirmSelect {

    @BindView(R2.id.et_search)
    EditText et_search;
    @BindView(R2.id.iv_clean)
    ImageView iv_clean;
    @BindView(R2.id.tv_search)
    TextView tv_search;
    @BindView(R2.id.ll_result)
    RelativeLayout ll_result;
    @BindView(R2.id.rlv_result)
    RecyclerView rlv_result;
    @BindView(R2.id.rlv_service)
    RecyclerView rlv_service;
    @BindView(R2.id.rl_header)
    RelativeLayout rl_header;
    @BindView(R2.id.tv_new)
    TextView tv_new;
    @BindView(R2.id.tv_result)
    TextView tv_result;
    @BindView(R2.id.tv_del)
    TextView tv_del;


    private String mobile;
    private X3HomeSearchAdapter saveAdapter;
    private List<NewServiceHeaderBean.AlreadyInPlanListBean> serviceList = new ArrayList<>();
    private long workBaseId;
    private List<NewServiceHeaderBean.AlreadyInPlanListBean> cacheList;
    private long questionBaseId;
    private X3NewSearchServiceItemAdapter itemAdapter;
    private List<NewServiceHeaderBean.AlreadyInPlanListBean> allList;
    private String decTitle;
    private NewServiceHeaderBean.AlreadyInPlanListBean changeServiceBean;
    private ObjectAnimator showSet;
    private ObjectAnimator hideSet;
    private X3PointDialog delDialog;
    private X3NewBottomMileOrTimeDialog mileOrTimeDialog;
    private X3BottomAffirmMileDialog mileDialog;
    private NewServiceHeaderBean.AlreadyInPlanListBean serviceListBean;
    private boolean needUpdateMile;
    private double newPerMiles;
    private double newCurrentMile;
    private long questionOptionId;
    private Map<String, AloneServiceListBean> aloneMap;
    private long carId;
    private List<NewServiceHeaderBean.AlreadyInPlanListBean> resultList = new ArrayList<>();
    private boolean isRemove = false;

    @Override
    protected int getLayoutId() {
        return R.layout.x3_activity_alone_search;
    }

    @Override
    protected void initView() {
        X3StatusBarUtil.darkMode(this);

        rl_header.setPadding(0, X3StatusBarUtil.getStatusBarHeight(this),0,0);

        workBaseId = getIntent().getIntExtra("workBaseId", 0);
        carId = getIntent().getIntExtra("carId", 0);
        decTitle = getIntent().getStringExtra("decTitle");

        questionBaseId = getIntent().getIntExtra("questionBaseId", 0);

        questionOptionId = getIntent().getIntExtra("questionOptionId", 0);

        needUpdateMile = getIntent().getBooleanExtra("needUpdateMile", false);

        mobile = (String) SpHelper.getData("mobile", "");

        et_search.addTextChangedListener(this);
        et_search.setOnEditorActionListener(this);
        /**
         * 进入弹出软件盘
         */
        etGetFouce();

        rlv_result.setLayoutManager(ChipsLayoutManager.newBuilder(this)
                .setOrientation(ChipsLayoutManager.HORIZONTAL)
                .setMaxViewsInRow(4)
                .build());

        rlv_service.setLayoutManager(new LinearLayoutManager(this));

        saveAdapter = new X3HomeSearchAdapter(this);
        rlv_result.setAdapter(saveAdapter);
        saveAdapter.setiOnSaveClick(this);

        itemAdapter = new X3NewSearchServiceItemAdapter(this);
        rlv_service.setAdapter(itemAdapter);
        itemAdapter.setiOnClickService(this);

        searchContent();

    }

    /**
     * 搜索本地缓存中添加的服务项目
     */
    @Override
    public void searchAloneCache() {
        allList = new ArrayList<>();
        if (mPresenter != null) {
            mPresenter.searchServiceByCarId(carId,et_search.getText().toString().trim());
        }

    }

    private void searchContent() {
        AloneSearchBean saveSearchBean = DaoSessionUtils.getInstance().selectAloneBean(mobile + "");
        if (saveSearchBean == null) {
            ll_result.setVisibility(View.GONE);
            return;
        }
        List<String> mList = saveSearchBean.getMList();
        if (X3StringUtils.isListEmpty(mList)) {
            ll_result.setVisibility(View.GONE);
            return;
        }
        if (saveAdapter != null) {
            saveAdapter.changeSearch(mList);
        }
    }

    @Override
    protected X3NewAloneServicePresenter createPresenter() {
        return new X3NewAloneServicePresenter();
    }

    @OnClick({R2.id.iv_back,R2.id.iv_clean,R2.id.tv_search,R2.id.tv_del})
    public void onViewClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            Intent intent = getIntent();
            intent.putExtra("resultList", (Serializable) resultList);
            intent.putExtra("isRemove", isRemove);
            setResult(RESULT_OK, intent);
            finish();
        } else if (id == R.id.iv_clean) {
            et_search.setText("");
            searchContent();
        } else if (id == R.id.tv_del) {
            DaoSessionUtils.getInstance().deleteAloneSearch();
            searchContent();
        } else if (id == R.id.tv_search) {/**
         * 搜索服务项目
         */
            String keyContent = et_search.getText().toString();
            if (X3StringUtils.isEmpty(keyContent)) {
                rlv_result.setVisibility(View.GONE);
                searchContent();
                return;
            }
            searchData(keyContent);
            /**
             * 搜索服务项目名称
             */
            searchCacheService(keyContent);
        }
    }

    private void searchKeyContent(String keyContent) {
        if (X3StringUtils.isEmpty(keyContent)) {
            return;
        }
        searchAloneCache();
    }

    /**
     * 搜索本地缓存服务数据
     */
    private void searchCacheService(String keyContent) {

         searchKeyContent(keyContent);
    }

    private void searchData(String keyContent) {
        AloneSearchBean saveSearchBean = DaoSessionUtils.getInstance().selectAloneBean(mobile + "");
        boolean isHaveSave = false;
        if (saveSearchBean == null) {
            saveSearchBean = new AloneSearchBean();
            saveSearchBean.setUserName(mobile);
            isHaveSave = true;
        }
        List<String> mList = saveSearchBean.getMList();
        if (X3StringUtils.isListEmpty(mList)) {
            mList = new ArrayList<>();
        }
        boolean isHave = false;
        for (String content : mList) {
            if (keyContent.equals(content)) {
                isHave = true;
            }
        }

        List<String> newList = new ArrayList<>(mList);
        if (!isHave) {
            if (newList.size() >= 10) {
                newList.remove(0);
            }
            newList.add(keyContent);
        }
        saveSearchBean.setMList(newList);

        if (isHaveSave) {
            DaoSessionUtils.getInstance().insertAloneSearch(saveSearchBean);
        } else {
            DaoSessionUtils.getInstance().updateAloneSearchBean(saveSearchBean);
        }
    }

    /**
     * 输入框获取焦点
     */
    protected void etGetFouce() {
        new Handler().postDelayed(() -> {
            if (et_search == null) {
                return;
            }
            et_search.setFocusable(true);
            et_search.setFocusableInTouchMode(true);
            et_search.requestFocus();
            InputMethodManager inputManager =
                    (InputMethodManager) et_search.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(et_search, 0);
        }, 1000);

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        String result = editable.toString();
        iv_clean.setVisibility(X3StringUtils.isEmpty(result) ? View.GONE : View.VISIBLE);
        tv_search.setTextColor(X3StringUtils.isEmpty(result) ? Color.parseColor("#666666") : Color.parseColor("#0077ff"));
        tv_search.setClickable(!X3StringUtils.isEmpty(result));
        if (X3StringUtils.isEmpty(result)) {
            rlv_service.setVisibility(View.GONE);
            rlv_result.setVisibility(View.VISIBLE);
            ll_result.setVisibility(View.VISIBLE);
            searchContent();
        }
    }

    @Override
    public void iOnSaveClick(String selectText) {
        et_search.setText("");
        if (X3StringUtils.isEmpty(selectText)) {
            return;
        }
        et_search.setText(selectText + "");
        et_search.setSelection(selectText.length());

        /**
         * TODO 搜索服务项目名称
         */
        searchCacheService(selectText);
    }



    @Override
    public void iOnCuteService(boolean isCute, NewServiceHeaderBean.AlreadyInPlanListBean serviceBean, int position) {
        serviceListBean = X3AloneServiceSearchUtils.searchNewAloneServiceBean(cacheList,serviceBean.serviceBaseSn);

        if (isCute) {
            /**
             * 将这个服务项目从缓存中去除
             */
            if (serviceListBean == null) {
                searchAloneCache();
                return;
            }
            boolean isHave = false;
            for (int i = 0; i < resultList.size(); i++) {
                NewServiceHeaderBean.AlreadyInPlanListBean aloneServiceListBean = resultList.get(i);
                if (aloneServiceListBean.serviceBaseSn.equals(serviceBean.serviceBaseSn) && !serviceBean.seleced) {
                    isHave = true;
                    resultList.remove(i);
                    resultList.add(i,aloneServiceListBean);
                    break;
                }
            }
            if(!isHave && !serviceBean.seleced){
                resultList.add(serviceBean);
            }

            if (serviceListBean == null) {
                searchAloneCache();
                return;
            }
            cacheList = X3AloneServiceSearchUtils.replaceNewAloneServiceBean(cacheList,serviceListBean.serviceBaseSn,serviceListBean);
            iOnPickerDismiss();

        }else {
            if (!needUpdateMile) {
                serviceListBean = addServiceItem(serviceBean, serviceListBean);
                iOnShowChangeServiceOne(serviceListBean, serviceListBean.reductionType);
            }else {
                // 否则需要先确认总里程和日均里程
                mileDialog = new X3BottomAffirmMileDialog(this);
                mileDialog.show();
                mileDialog.setWorkBaseId(workBaseId,null);
                mileDialog.setiOnClickAffirmMiles((currentMiles1, perMiles1) -> {
                    // 确认完总里程和日均里程了
                    needUpdateMile = false;

                    newPerMiles = Double.parseDouble(X3StringUtils.formatDouble(perMiles1));
                    newCurrentMile = Double.parseDouble(X3StringUtils.formatDouble(currentMiles1));

                    CameraBean cameraBean = new CameraBean();
                    cameraBean.currentMiles = newCurrentMile;
                    cameraBean.perMiles = newPerMiles;
                    EventBus.getDefault().post(new CameraBean(X3Constent.CODE_ALONE_CHANGE_NEED_UPDATE,cameraBean));

                    serviceBean.currentMiles = newCurrentMile;
                    serviceBean.perMiles = newPerMiles;

                    serviceListBean = addServiceItem(serviceBean, serviceListBean);
                    if (itemAdapter != null) {
                        itemAdapter.refreshMiles(newCurrentMile, newPerMiles);
                    }

                    iOnShowChangeServiceOne(serviceListBean,serviceListBean.reductionType);
                });
            }
        }
    }

    public void iOnShowChangeServiceOne(NewServiceHeaderBean.AlreadyInPlanListBean  changeServiceBean,String remindType) {
        this.changeServiceBean = changeServiceBean;
        modifyMileOrTime(changeServiceBean,remindType);
    }

    private NewServiceHeaderBean.AlreadyInPlanListBean addServiceItem(NewServiceHeaderBean.AlreadyInPlanListBean serviceBean,NewServiceHeaderBean.AlreadyInPlanListBean serviceListBean1) {
        NewServiceHeaderBean.AlreadyInPlanListBean newServiceBean = serviceListBean1;
        if (newServiceBean == null) {
            newServiceBean = new NewServiceHeaderBean.AlreadyInPlanListBean();
            newServiceBean.nextReplaceCycleKm = serviceBean.nextReplaceCycleKm;
            newServiceBean.serviceBaseName = serviceBean.serviceBaseName;
            newServiceBean.serviceBaseSn = serviceBean.serviceBaseSn;
            newServiceBean.currentMiles = serviceBean.currentMiles;
            newServiceBean.perMiles = serviceBean.perMiles;
            newServiceBean.seleced = serviceBean.seleced;
            newServiceBean.carId = serviceBean.carId;
        }else {
            cacheList = X3AloneServiceSearchUtils.replaceNewAloneServiceBean(cacheList,newServiceBean.serviceBaseSn,newServiceBean);
        }
        return newServiceBean;
    }


    @Override
    public void iOnShowChangeService(String sn,String remindType,double currentMiles,double perMiles) {
        changeServiceBean = X3AloneServiceSearchUtils.searchNewAloneServiceBean(cacheList,sn);
        changeServiceBean.currentMiles = currentMiles;
        changeServiceBean.perMiles = perMiles;
        modifyMileOrTime(changeServiceBean,remindType);
    }

    private void modifyMileOrTime(NewServiceHeaderBean.AlreadyInPlanListBean  changeServiceBean,String remindType) {
        if (changeServiceBean.currentMiles <= 0 && changeServiceBean.currentMiles <= 1) {
            changeServiceBean.perMiles = newPerMiles;
            changeServiceBean.currentMiles = newCurrentMile;
        }
        AloneServiceListBean aloneServiceListBean = new AloneServiceListBean();
        aloneServiceListBean.setPerMiles(changeServiceBean.perMiles);
        aloneServiceListBean.setCurrentMiles(changeServiceBean.currentMiles);
        aloneServiceListBean.setRecommendSafeMiles(changeServiceBean.nextReplaceCycleKm);
        aloneServiceListBean.setTouchServiceSn(changeServiceBean.serviceBaseSn);
        aloneServiceListBean.setWarningDate(changeServiceBean.warningDate);
        aloneServiceListBean.setReductionType(changeServiceBean.reductionType);
        aloneServiceListBean.setCarId(changeServiceBean.carId);
        aloneServiceListBean.setSeleced(true);
        aloneServiceListBean.setTouchServiceBaseName(changeServiceBean.serviceBaseName);
        mileOrTimeDialog = new X3NewBottomMileOrTimeDialog(this,1);
        mileOrTimeDialog.show();
        mileOrTimeDialog.showCurrentMile(aloneServiceListBean,remindType);
        mileOrTimeDialog.setiOnAffirmSelect(this);
    }

    @Override
    public void iOnShowDelete(int position, String sn) {
        NewServiceHeaderBean.AlreadyInPlanListBean serviceListBean = X3AloneServiceSearchUtils.searchNewAloneServiceBean(cacheList, sn);
        if (serviceListBean == null) {
            return;
        }
            delDialog = new X3PointDialog(this, "", getString(R.string.x3_delete_add_service), getString(R.string.x3_cancel_info), getString(R.string.x3_affirm_info));
            delDialog.show();
            delDialog.setRightClick(view -> {
                delDialog.dismiss();
                if (itemAdapter != null) {
                    itemAdapter.deleteService(position, true, true);
                }
            });
    }

    @Override
    public void iOnAffirmMiles(AloneServiceListBean listBean) {
            NewServiceHeaderBean.AlreadyInPlanListBean alreadyInPlanListBean = new NewServiceHeaderBean.AlreadyInPlanListBean();
            alreadyInPlanListBean.serviceBaseSn =listBean.getTouchServiceSn();
            alreadyInPlanListBean.currentMiles = listBean.getCurrentMiles();
            alreadyInPlanListBean.perMiles = listBean.getPerMiles();
            alreadyInPlanListBean.carId = listBean.getCarId();
            alreadyInPlanListBean.warningDate = listBean.getWarningDate();
            alreadyInPlanListBean.nextReplaceCycleKm = listBean.getRecommendSafeMiles();
            alreadyInPlanListBean.reductionType = listBean.getReductionType();
            alreadyInPlanListBean.seleced = true;
            alreadyInPlanListBean.serviceBaseName = listBean.getTouchServiceBaseName();
            boolean isHave = false;
            for (int i = 0; i < resultList.size(); i++) {
                NewServiceHeaderBean.AlreadyInPlanListBean aloneServiceListBean = resultList.get(i);
                if (aloneServiceListBean.serviceBaseSn.equals(listBean.getTouchServiceSn())) {
                    isHave = true;
                    resultList.remove(i);
                    resultList.add(i,alreadyInPlanListBean);
                    break;
                }
            }
            if(!isHave){
                resultList.add(alreadyInPlanListBean);
            }

            if (itemAdapter != null) {
                itemAdapter.changeMilesService(alreadyInPlanListBean);
            }
    }

    @Override
    public void iOnPickerDismiss() {
        CameraBean cameraBean = new CameraBean(X3Constent.CODE_ALONE_ADD_SERVICE_REQUEST,cacheList);
        EventBus.getDefault().post(cameraBean);
    }




    @Override
    protected void onDestroy() {
        if (showSet != null) {
            showSet.cancel();
        }
        if (hideSet != null) {
            hideSet.cancel();
        }
        super.onDestroy();
    }

    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            String keyContent = et_search.getText().toString();
            if (X3StringUtils.isEmpty(keyContent)) {
                //ToastUtils.showMessage(getString(R.string.input_content) + "~");
                return true;
            }

            tv_search.performClick();
        }
        return true;
    }

    @Override
    public void searchServiceByCarIdSus(List<NewServiceHeaderBean.AlreadyInPlanListBean> mList) {
        this.serviceList = mList;
        this.allList = serviceList;
        this.cacheList = mList;
        iOnPickerDismiss();

        ll_result.setVisibility(View.GONE);
        rlv_service.setVisibility(View.VISIBLE);
        for (int i = 0;i < serviceList.size();i++){
            if(serviceList.get(i).seleced){
                resultList.add(serviceList.get(i));
            }
        }

        if (itemAdapter != null) {
            itemAdapter.changeServiceItem(serviceList);
        }

        switch (serviceList.size()) {
            case 0:
                tv_new.setText(getString(R.string.x3_home_no_select));
                break;
            case 1:
                tv_new.setText(String.format(getString(R.string.x3_home_select_work),serviceList.size()));
                break;
            default:
                tv_new.setText(String.format(getString(R.string.x3_home_select_works),serviceList.size()));
                break;
        }

        PropertyValuesHolder show_alpha = PropertyValuesHolder.ofFloat("alpha", 0f, 1f);
        PropertyValuesHolder show_transY = PropertyValuesHolder.ofFloat("translationY", tv_new.getTranslationY(), 0.0f);
        showSet = ObjectAnimator.ofPropertyValuesHolder(tv_new, show_alpha, show_transY);
        showSet.setStartDelay(500);
        showSet.setDuration(500);

        PropertyValuesHolder hide_alpha = PropertyValuesHolder.ofFloat("alpha", 1f, 0f);
        hideSet = ObjectAnimator.ofPropertyValuesHolder(tv_new, hide_alpha);
        hideSet.setStartDelay(500);
        hideSet.setDuration(300);
        hideSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                tv_new.setVisibility(View.INVISIBLE);
                tv_new.setTranslationY(-X3ScreenUtils.dipToPx(30, X3NewAloneSearchActivity.this));
            }
        });

        showSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                hideSet.start();
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                tv_new.setVisibility(VISIBLE);
            }
        });
        showSet.start();


    }

    @Override
    public long providerWorkBaseId() {
        return workBaseId;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            Intent intent = getIntent();
            intent.putExtra("resultList",(Serializable)resultList);
            intent.putExtra("isRemove",isRemove);
            setResult(RESULT_OK,intent);
            finish();
        }
            return super.onKeyDown(keyCode, event);

    }

}